package network;

import java.io.IOException;
import java.net.Socket;
import model.Game;
import model.Player;
import model.Smurf;
import model.World;

public class Client2{

	private Socket socket;
	private Thread thread;
	private int updateInterval;
	
	public Client2(final int id, String ip){
		try {
			socket = Network.createConnection(ip, 2600+id);
			thread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						int id = Game.getInstance().getId();
						Player p = World.getInstance().getPlayer(id);
						Smurf s = p.getSmurf();
						while(true){
							long start = System.currentTimeMillis();
						
							NetworkPackage npp = new NetworkPackage(id, s.getX(), s.getY(), s.getXSpeed(), s.getYSpeed());
							Network.sendObject(npp, socket);						
							
							Object object = Network.readObject(socket);										
							NetworkPackage[] nps = (NetworkPackage[])object;						
							for(NetworkPackage np : nps){
								if(np != null){
									if(np.getId() != id){
										Smurf smurf = new Smurf("TEST", np.getX(), np.getY(), np.getXSpeed(), np.getYSpeed());
										World.getInstance().setPlayer(np.getId(),new Player(np.getId(), "TEST", smurf));
									}
								}
							}
							long end = System.currentTimeMillis();
							System.out.println(end-start);
							try {
								if((end-start)<(updateInterval)){
									Thread.sleep((updateInterval)-(end-start));
								}else{
									System.out.println("Lagging after with "+((updateInterval)-(end-start))+" millis");
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}				
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void start(int updateInterval){
		this.updateInterval = updateInterval;
		thread.start();		
	}
}
